
export default {
	namespaced:true,
	state:()=>({
		popShow:false,
		popData:null, //弹窗数据
		cartList:[],
		editIdx:-1  //标志新增、编辑
	}),
	getters:{
		allInfo(state){
			let allCheck = true  //全选状态
			let allPrice = 0
			let allNum = 0
			state.cartList.forEach(item=>{
				if(!item.isCheck){
					allCheck = false
				}
				let {gnum,list,dropIdx} = item
				if(item.isCheck){
					allPrice += list[dropIdx].price * gnum
				}
				allNum += gnum
			})
			// getters可以检测到cartList的变化，同步更新本地存储
			uni.setStorage({
				key:'uni-cart-list',
				data:state.cartList
			})
			return {
				allCheck,
				allPrice,
				allNum
			}
		}
	},
	mutations:{
		popShowMut(state,bool){
			state.popShow = bool
		},
		// 为弹窗组件赋值
		popDataMut(state,cakeObj){
			state.popData = cakeObj
		},
		//新增购物车
		cartAddMut(state,cartObj){
			let {cartList} = state
			let {dropIdx,id,gnum} = cartObj
			if(state.editIdx!=-1){ //编辑购物车
				state.cartList[state.editIdx] = cartObj
				return
			}
			for(let i=0;i<cartList.length;i++){
				// 新增同类商品
				if(cartList[i].id==id&&cartList[i].dropIdx==dropIdx){
					state.cartList[i].gnum += gnum
					return
				}
			}
			state.cartList.push(cartObj) //新增新商品
		},
		cartInitMut(state,cartList){
			try{
				let list = uni.getStorageSync('uni-cart-list')
				if(list){
					console.log('提取cartList',list);
					state.cartList = list
				}else{
					throw new Error('提取失败')
				}
			}catch(e){
				//TODO handle the exception
				console.log('提取购物车列表失败');
			}
		},
		//单选
		cartCheckMut(state,idx){
			state.cartList[idx].isCheck = !state.cartList[idx].isCheck
		},
		//全选
		cartAllCheckMut(state,bool){
			state.cartList.forEach(item=>{
				item.isCheck = !bool
			})
		},
		//删除
		cartDelMut(state,idx){
			state.cartList.splice(idx,1)
		},
		//区分新增、编辑
		editIdxMut(state,idx){
			state.editIdx = idx
		}
	}
}